<?php
/*-----------------------------------------------------
    NewsLister post.php
	
    @package NewsLister
	@since 1.0
	
	@version    1.0.0
	@copyright Tenderfeel
	@author Tenderfeel(tenderfeel@gmail.com)
	@link http://tenderfeel.xsrv.jp/ 
------------------------------------------------------*/
require_once("config.php");
require_once("FastJSON.class.php");

if(isset($_POST["mode"]) && $_POST["mode"] != ""){
	switch($_POST["mode"]){
		case "save":
			if($_POST["comment"] != ""){
				save_data();
			}
		break;
		
		case "delete":
			if($_POST["index"] != ""){
				delete_data($_POST["index"]);
			}
		break;
		
	}
  
}

if(isset($_GET["mode"],$_GET["callback"],$_GET["page"]) && $_GET["mode"] == "load"){
	$callback = $_GET["callback"];
	/*$logdata = load_data();
	print $callback . "({\"items\":".json_encode($logdata)."});";*/
	
	$logdata = get_data($_GET["page"],DISPMAX);
	print $callback . "({\"items\":".FastJSON::convert($logdata[0]).",\"pagenum\":".ceil($logdata[1]).",\"current\":".$_GET["page"]."});";
}


/**
 * 削除処理
 * 
 -----------------------------------------------------*/
function delete_data($index)
{
	$logdata = load_data();
	$contents = array();
	
	foreach ($logdata as $line => $data) {
		if($data["id"] != $index){
			$contents[] = $data;
		}
	}
	
	write_data($contents);
	
	//createJSON($contents);
	
	print "削除しました";
}

/**
 *　ローディング
------------------------------------------------------*/
function load_data()
{	
	$contents = array();
	
	$fp = fopen(ABSDIR.LOGFILE, "r");
	flock($fp, LOCK_EX);
	
	while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
		$contents[] = array_combine(array("id","date","comment"),$data);
	}
	
  	flock($fp, LOCK_UN);
	fclose($fp);
	
	return $contents;
}

function to_utf8($str)
{
	return mb_convert_encoding($str,"UTF-8","UTF-8");
}

/*
 * ローディングポスト
--------------------------------------------------------*/
function get_data($page = 0, $max)
{

	$logdata = load_data();
	$logcount= count($logdata);
	$count = count_maxpage($max, $logcount);
	$output = disp_data($logdata,$page, $max, $count);
	$paged = paged($page, $max, $count);
	
	return array($output,$count['max']);
}
/**
 * ライティング
------------------------------------------------------*/
function write_data($contents)
{	
	$logcount = count($contents);

	$fp = fopen(ABSDIR.LOGFILE, "w");
	flock($fp, LOCK_EX);
	
	//書き込み
	for($i = 0; $i < SAVEMAX ; $i++){
		if($logcount <= $i) continue;
		$data = array_values($contents[$i]);
		fwrite($fp,$data[0].",".$data[1].",\"".$data[2]."\"\n");
		
	}
	
	flock($fp, LOCK_UN);
	fclose($fp);
	
	return true;
}

/**
 * 保存処理
 -----------------------------------------------------*/
function save_data()
{
	
	$new_line = array("id"=>time(),
					  "date"=>strtotime($_POST["year"]."-".$_POST["month"]."-".$_POST["day"]." ".$_POST["hour"].":".$_POST["min"].":00"),
					  "comment"=>comment_format($_POST["comment"])
					  );
	
	//ログの読み込みと新行の追加
	$contents = load_data();
	$contents[]= $new_line;//NEW LINE
	
	$logcount = count($contents);
	
	for($n = 0; $n < $logcount ;$n++){
		$id[$n] = $contents[$n]["id"];
		$postdate[$n]= $contents[$n]["date"].":00";
	}
	
	array_multisort($postdate,SORT_DESC,$id,SORT_DESC,$contents);//並び替え
	
	write_data($contents);
	
	//print json_encode($new_line); //admin.js用
	
	print FastJSON::convert($new_line);
}

/**
 * コメントの整形
----------------------------------------------------*/
function comment_format($str)
{
	$str = str_replace("\0", "", trim($str));
	$str = nl2br(htmlentities(strip_tags($_POST["comment"]),ENT_QUOTES,"UTF-8"));
	$str = str_replace(array("\r\n", "\n\n","\r", "\n"), "", $str);
	$str = str_replace(array("	",","),array("\t",'&#044;'),$str);

	if (get_magic_quotes_gpc()) {
		$str = stripslashes($str);
	}
	
	return $str;
}


//pagination
function disp_data($logdata,$page=0,$limit,$count){
	
	$start = $page * $count['lng'];
	$end   = ($page * $count['lng']) + $count['lng'];

	for($i=$start;$i<$end;$i++){
		
		if($i >= $count['row']){break;}
		
		$output[] = $logdata[$i];
		
	}
	return $output;
}

/* ページ送り*/
function paged($page=0,$limit,$count)
{
	$paged['current'] = $page;
	$paged['total'] = $count['row'];
	$paged['start'] = ($page*$count['lng'])+1;
	$paged['lng']=$count['lng'];
	
    if($count['max'] > $page){
        $paged["next"] = $page + 1;
    }else{
        $paged["next"] = false;
    }
	
	$paged['max'] = ceil($count['max']);
	
    if($page - 1 >= 0){
        $paged["previous"] = $page - 1;
    }
	
    return $paged; 
}

/* ページ数カウント*/
function count_maxpage($limit, $logcount)
{
	
	$count['lng'] = $limit; //１ページあたりの表示数
	$count['row'] = $logcount; //データ数
		
	//全ページ数を求める処理
	$count['max'] = $count['row']/$count['lng'];
	$tmp = (int)$count['max'];
	if($maxpage>$tmp){$count['max']=$tmp+1;}
	$count['max']--;
	
	return $count;
}

//最終更新日取得(use feed.php)
function get_lastpostmodified()
{
	$stmp = filemtime(ABSDIR.LOGFILE);
	return gmdate('D, d M Y H:i:s',$stmp)." GMT";
}

//ファイルURI(use feed.php)
function self_link() {
	$host = parse_url(SITEURL);
	echo 'http'. ( (isset($_SERVER['https']) && $_SERVER['https'] == 'on') ? 's' : '' ) . '://'.$host['host'].str_replace("&","&amp;",stripslashes($_SERVER['REQUEST_URI']));
}
?>